import React from 'react';
import './applyOrderList.less';
import { Link } from 'react-router';
import { Breadcrumb, Row, Col, Input, DatePicker, Select, Button, Table, Modal, Pagination, message } from 'antd';
import moment from 'moment';
import $ from 'jquery';
import Config from '../../common/config';

const { RangePicker } = DatePicker;
const Option = Select.Option;
const config = new Config();
const InputGroup = Input.Group;
const token = sessionStorage.getItem('token');
class applyOrderList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userId: JSON.parse(sessionStorage.getItem('UserInfo')).userid, // 操作人用户ID
      data: [], // 订单数据
      text: '', // 搜索值
      date: [], // 时间
      status: undefined, // 处理结果
      page: 1, // 当前页
      pageSize: 10, // 每页显示的条数
      total: 0, // 总数
      examineOrder: {}, // 审核的订单
      examineVisible: false, // 审核的模态框显示
      examineResult: '2', // 审核结果，默认为通过
      examineRemark: '', // 审核备注
      remarkErrowMsg: '', // 错误提示信息
    }
    this.InputText = this.InputText.bind(this);
    this.changeDate = this.changeDate.bind(this);
    this.selectHandleResult = this.selectHandleResult.bind(this);
    this.hiddenExamine = this.hiddenExamine.bind(this);
    this.onChangePage = this.onChangePage.bind(this);
    this.selectExamineResult = this.selectExamineResult.bind(this);
    this.changeRemark = this.changeRemark.bind(this);
    this.examine = this.examine.bind(this);
  }

  componentDidMount() {
    this.getData();
  }

  //获取订单数据
  getData() {
    const date = this.state.date;
    const beginDate = date[0] ? date[0].format('YYYY-MM-DD') : '';
    const endDate = date[1] ? date[1].format('YYYY-MM-DD') : '';
    $.ajax({
      url: `${config.JuseOrder}/applyOrder/list`,
      type: 'get',
      headers: {
        'Authorization': 'Bearer ' + token,
      },
      data: {
        text: this.state.text,
        beginDate,
        endDate,
        status: this.state.status,
        page: this.state.page,
        pageSize: this.state.pageSize
      },
      success: (res) => {
        console.log('申请列表', res);
        if (res.code === 200) {
          res.data.rows.forEach((item, index) => {
            item.key = index + 1 + (this.state.page - 1) * this.state.pageSize;
          });
          this.setState({
            data: res.data.rows,
            total: res.data.count
          });
        }
      }
    });
  }

  // 表头
  getColumns() {
    return [{
      title: '序号',
      width: '4%',
      dataIndex: 'key'
    }, {
      title: '订单编号',
      width: '12%',
      render(record) {
        return <Link to={'/applyOrderDetail/' + record.orderId}>{record.orderId}</Link>
      }
    }, {
      title: '退款编号',
      width: '12%',
      dataIndex: 'refundId'
    }, {
      title: '交易金额',
      width: '9%',
      render(record) {
        return `${record.money}(${record.paymentMethod})`
      }
    }, {
      title: '退款金额',
      width: '9%',
      dataIndex: 'refundMoney'
    }, {
      title: '服务类型',
      width: '7%',
      dataIndex: 'serviceType'
    }, {
      title: '申请原因',
      width: '15%',
      dataIndex: 'refundReason'
    }, {
      title: '申请时间',
      width: '9%',
      render(record) {
        return moment(Number(record.refundDate)).format('YYYY-MM-DD HH:mm')
      }
    }, {
      width: '7%',
      title: '处理结果',
      render(record) {
        let text;
        switch (record.status) {
          case 1:
            text = '待审核';
            break;
          case 2:
            text = '审核通过';
            break;
          case 3:
            text = '审核不通过';
            break;
        }
        return text;
      }
    }, {
      width: '9%',
      title: '处理时间',
      render(record) {
        if (record.handleDate) {
          return moment(Number(record.handleDate)).format('YYYY-MM-DD HH:mm')
        }
      }
    }, {
      width: '7%',
      title: '操作',
      render: (record) => {
        if (record.status === 1) {
          return <a href='javascript:void(0)' onClick={this.showExamine.bind(this, record)}>审核</a>
        }
      }
    }];
  }

  // 输入搜索值
  InputText(e) {
    this.setState({
      text: e.target.value
    });
  }

  // 选择日期
  changeDate(date) {
    this.setState({
      date
    });
  }

  // 选择处理结果
  selectHandleResult(value) {
    this.setState({
      status: value
    });
  }

  // 搜索/清空
  filterOrders(key) {
    if (key) {
      // 搜索
      this.setState({
        page: 1
      }, () => {
        this.getData();
      });
    } else {
      // 清空
      this.setState({
        text: '',
        date: [],
        status: undefined
      }, () => {
        this.getData();
      });
    }
  }

  // 切换分页
  onChangePage(page) {
    this.setState({
      page
    }, () => {
      this.getData();
    });
  }

  // 显示审核模态框
  showExamine(order) {
    this.setState({
      examineVisible: true,
      examineOrder: order,
      examineResult: '2',
      remarkErrowMsg: '',
      examineRemark: ''
    });
  }

  // 隐藏审核模态框
  hiddenExamine() {
    this.setState({
      examineVisible: false,
      examineOrder: {},
    });
  }

  // 选择审核结果
  selectExamineResult(value) {
    this.setState({
      examineResult: value
    });
  }

  // 选择备注
  changeRemark(e) {
    let remarkErrowMsg = this.state.remarkErrowMsg;
    if (e.target.value) {
      remarkErrowMsg = '';
    }
    this.setState({
      remarkErrowMsg,
      examineRemark: e.target.value
    });
  }

  // 审核
  examine() {
    const examineRemark = this.state.examineRemark;
    if (!examineRemark) {
      return this.setState({
        remarkErrowMsg: '请填写备注'
      });
    }
    console.log(this.state.examineOrder.serviceType);
    if (this.state.examineOrder.serviceType === '取消预约') {
      console.log(1);
      $.ajax({
        url: `${config.JuseOrder}/applyOrder/examineReservation`,
        type: 'post',
        headers: {
          'Authorization': 'Bearer ' + token,
        },
        data: {
          handlePerson: this.state.userId,
          refundId: this.state.examineOrder.refundId,
          status: this.state.examineResult,
          examineRemark
        },
        success: (data) => {
          console.log('审核取消预约', data);
          if (data.code === 200) {
            this.setState({
              examineVisible: false,
              examineOrder: {},
              examineRemark: ''
            });
            this.getData();
          } else {
            message.error(data.mes);
          }
        }
      });
    } else if (this.state.examineOrder.serviceType === '代客退款') {
      console.log(2);
      $.ajax({
        url: `${config.JuseOrder}/applyOrder/examineRefund`,
        type: 'post',
        headers: {
          'Authorization': 'Bearer ' + token,
        },
        data: {
          handlePerson: this.state.userId,
          refundId: this.state.examineOrder.refundId,
          status: this.state.examineResult,
          examineRemark
        },
        success: (data) => {
          console.log('审核取消预约', data);
          if (data.code === 200) {
            this.setState({
              examineVisible: false,
              examineOrder: {},
              examineRemark: ''
            });
            this.getData();
          } else {
            message.error(data.mes);
          }
        }
      });
    } else if (this.state.examineOrder.serviceType === '代客取消订单') {
      console.log(3);
      $.ajax({
        url: `${config.JuseOrder}/applyOrder/examineCancel`,
        type: 'post',
        headers: {
          'Authorization': 'Bearer ' + token,
        },
        data: {
          handlePerson: this.state.userId,
          refundId: this.state.examineOrder.refundId,
          status: this.state.examineResult,
          examineRemark
        },
        success: (data) => {
          console.log('审核取消订单', data);
          if (data.code === 200) {
            this.setState({
              examineVisible: false,
              examineOrder: {},
              examineRemark: ''
            });
            this.getData();
          } else {
            message.error(data.mes);
          }
        }
      });
    } else if (this.state.examineOrder.serviceType === '代客拒收') {
      console.log(4);
      $.ajax({
        url: `${config.JuseOrder}/applyOrder/examineValetRejection`,
        type: 'post',
        headers: {
          'Authorization': 'Bearer ' + token,
        },
        data: {
          handlePerson: this.state.userId,
          refundId: this.state.examineOrder.refundId,
          status: this.state.examineResult,
          examineRemark
        },
        success: (data) => {
          console.log('审核代客拒收', data);
          if (data.code === 200) {
            this.setState({
              examineVisible: false,
              examineOrder: {},
              examineRemark: ''
            });
            this.getData();
          } else {
            message.error(data.mes);
          }
        }
      });
    }
  }

  render() {
    const columns = this.getColumns();
    return (
      <div className='contentBox clearfix'>
        <div className="member-content-Search">
          <div className='breadcrumb'>
            <Breadcrumb separator=">">
              <Breadcrumb.Item>订单管理</Breadcrumb.Item>
              <Breadcrumb.Item>申请列表</Breadcrumb.Item>
            </Breadcrumb>
          </div>
          <div className='orderfilter'>
            <div className="member-content-Search" style={{ marginBottom: 20 }}>
              <div className='addetd addetd-z' style={{ zIndex: 1 }}>
                <Input addonBefore='请输入订单编号、退货编号' placeholder="请输入" value={this.state.text} onChange={this.InputText} />
              </div>
              <div className='addetd addetd1 addetd2'>
                <Input className='addetd-a-r' addonBefore="申请时间" placeholder="请输入" value={this.state.Inkey} onChange={(e) => this.changeInkey(e)} />
                <RangePicker
                  format='YYYY-MM-DD'
                  placeholder={['请选择日期', '请选择日期']}
                  onChange={this.changeDate}
                  value={this.state.date}
                />
              </div>
              <div className='addetd addetd1 addetd-ght addetd-ght-1'>
                <InputGroup compact>
                  <Input addonBefore="处理结果" />
                  <Select placeholder='请选择' value={this.state.status} onChange={this.selectHandleResult} allowClear>
                    <Option value='1'>待审核</Option>
                    <Option value='2'>审核通过</Option>
                    <Option value='3'>审核不通过</Option>
                  </Select>
                </InputGroup>
              </div>
              <Button className='ant-btn-primary' icon='search' onClick={this.filterOrders.bind(this, 1)}>搜索</Button>
              <Button className='ant-btn-primary' icon='sync' onClick={this.filterOrders.bind(this, 0)}>重置</Button>
            </div>
          </div>
        </div>
        <div className='allgoods-table clearfix'>
          <Table columns={columns} dataSource={this.state.data} pagination={false} bordered />
        </div>
        <div className='goods-label-let clearfix'>
          <div className="floor-ppagi">
            {
              this.state.total == 0 ?
                <p className="floor-ppagip">
                  共{this.state.total}条记录
              </p> :
                <p className="floor-ppagip">
                  当前显示
                {this.state.pageSize * (this.state.page - 1) + 1}—
                {this.state.pageSize * this.state.page < this.state.total ? this.state.pageSize * this.state.page : this.state.total}条记录，
                共{this.state.total}条记录
              </p>
            }
            <Pagination current={this.state.page} total={this.state.total || 1} defaultPageSize={this.state.pageSize} onChange={this.onChangePage.bind(this)} />
          </div>
        </div>
        <Modal
          visible={this.state.examineVisible}
          onCancel={this.hiddenExamine}
          style={{ width: 1000 }}
          footer={null}
          className={'tanchu'}
          maskClosable={false}
        >
          <p className='jiacev'>审核</p>
          <Row className='tanchu1'>
            <Col span={6}>
              <span className='wgdbrv'>收货人：</span>
              <span>{this.state.examineOrder['order.consigneeName']}</span>
            </Col>
            <Col span={6}>
              <span className='wgdbrv'>联系方式：</span>
              <span>{this.state.examineOrder['order.consigneePhone']}</span>
            </Col>
            <Col span={6}>
              <span className='wgdbrv'>支付状态：</span>
              <span>
                {
                  this.state.examineOrder['order.isAlreadyPay']
                    ?
                    '已支付'
                    :
                    '待买家付款'
                }
              </span>
            </Col>
            <Col span={6}>
              <span className='wgdbrv'>服务类型：</span>
              <span>{this.state.examineOrder.serviceType}</span>
            </Col>
          </Row>
          <ul>
            <li>
              <Row className='erhgnt'>
                <Col span={5}>商品图片</Col>
                <Col span={5}>商品内码</Col>
                <Col span={5}>商品单价</Col>
                <Col span={5}>商品数量</Col>
                <Col span={4}>小计</Col>
              </Row>
            </li>
            {
              this.state.examineOrder.productList && this.state.examineOrder.productList.map((item, index) => {
                return <li key={index}>
                  <Row className='tanchu2'>
                    <Col style={{ height: 50 }} span={5}><img src={item.imageUrl + item.listImage} style={{ width: 50, height: 50 }} /></Col>
                    <Col span={5}>{item.productId}</Col>
                    <Col span={5}>{item.paidPrice}</Col>
                    <Col span={5}>{item.buyNumber}</Col>
                    <Col span={4}>{(item.paidPrice * item.buyNumber).toFixed(2)}</Col>
                  </Row>
                </li>
              })
            }
          </ul>
          <Row>
            <Col>
              <span className='wgdbrv'>申请原因：</span>
              <span>{this.state.examineOrder.refundReason}</span>
            </Col>
          </Row>
          {
            this.state.examineOrder.requireRefund
              ?
              <Row className='tanchu1'>
                <Col span={6}>
                  <span className='wgdbrv'>退款途径：</span>
                  <span>{this.state.examineOrder.refundWay}</span>
                </Col>
                <Col span={6}>
                  <span className='wgdbrv'>账户名：</span>
                  <span>{this.state.examineOrder.refundUserName}</span>
                </Col>
                <Col span={6}>
                  <span className='wgdbrv'>退款账号：</span>
                  <span>{this.state.examineOrder.refundAccountNumber}</span>
                </Col>
                <Col span={6}>
                  <span className='wgdbrv'>退款金额：</span>
                  <span>{this.state.examineOrder.refundMoney}</span>
                </Col>
              </Row>
              :
              ''
          }
          <Row>
            <Col>
              <span className='wgdbrv'>操作</span>
            </Col>
          </Row>
          <Row>
            <Col>
              <span className='wgdbrv'>处理结果</span>
              <span>
                <Select placeholder='请选择' value={this.state.examineResult} onChange={this.selectExamineResult} style={{ width: 120 }}>
                  <Option value='2'>通过</Option>
                  <Option value='3'>不通过</Option>
                </Select>
              </span>
            </Col>
          </Row>
          <Row>
            <Col>
              <span className='wgdbrv'>备注：</span>
              <Input type='textarea' value={this.state.examineRemark} placeholder='必填' onChange={this.changeRemark} />
              <p>{this.state.remarkErrowMsg}</p>
            </Col>
          </Row>
          <Row>
            <Col span={1} className='shenhe'>
              <Button onClick={this.examine} >审核</Button>
            </Col>
          </Row>
        </Modal>
      </div>
    )
  }
}

export default applyOrderList;
